<style lang="less">
    @import './own-space.less';
</style>

<template>
    <div>
        <Card>
            <p slot="title">
                <Icon type="person"></Icon>
                个人信息
            </p>
            <div>
                <Form
                        ref="userForm"
                        :model="userForm"
                        :label-width="100"
                        label-position="right"
                        :rules="inforValidate">
                    <FormItem label="账号：">
                        <span>{{ uid }}</span>
                    </FormItem>
                    <FormItem label="用户名：">
                        <span>{{ userForm.name }}</span>
                    </FormItem>
                    <FormItem label="账号权限：">
                        <span>{{ userForm.role }}</span>
                    </FormItem>
                    <FormItem label="登录密码：">
                        <a href="#" type="primary" style="{color:#000;text-decoration:underline;margin-left: 5px;}" @click="showEditPassword">点击修改密码</a>
                    </FormItem>
                </Form>
            </div>
        </Card>
        <Modal v-model="editPasswordModal" :closable='false' :mask-closable=false :width="500"
               @on-cancel="resetForm('editPasswordForm')">
            <h3 slot="header" style="color:#2D8CF0">修改密码</h3>
            <Form ref="editPasswordForm" :model="editPasswordForm" :label-width="100" label-position="right" :rules="passwordValidate">
                <FormItem label="原密码" prop="oldPass" :error="oldPassError">
                    <Input v-model="editPasswordForm.oldPass" placeholder="请输入现在使用的密码"></Input>
                </FormItem>
                <FormItem label="新密码" prop="newPass">
                    <Input v-model="editPasswordForm.newPass" placeholder="请输入新密码，至少6位字符"></Input>
                </FormItem>
                <FormItem label="确认新密码" prop="rePass">
                    <Input v-model="editPasswordForm.rePass" placeholder="请再次输入新密码"></Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancelEditPass">取消</Button>
                <Button type="primary" @click="saveEditPass">保存</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {modPwd} from '../../controllers/account';
    import Cookies from 'js-cookie';
    import Constant from '../../libs/constants';

    export default {
        name: 'own-space',
        data() {
            const validePhone = (rule, value, callback) => {
                var re = /^1[0-9]{10}$/;
                if (!re.test(value)) {
                    callback(new Error('请输入正确格式的手机号'));
                } else {
                    callback();
                }
            };
            const valideRePassword = (rule, value, callback) => {
                if (value !== this.editPasswordForm.newPass) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            };
            return {
                userForm: {
                    name: '',
                    role: '',
                    cellphone: '',
                    company: '',
                    department: ''
                },
                uid: '',  // 登录用户的userId
                securityCode: '',  // 验证码
                phoneHasChanged: false,  // 是否编辑了手机
                save_loading: false,
                identifyError: '',  // 验证码错误
                editPasswordModal: false, // 修改密码模态框显示
                oldPassError: '',
                identifyCodeRight: false,  // 验证码是否正确
                hasGetIdentifyCode: false,  // 是否点了获取验证码
                canGetIdentifyCode: false,  // 是否可点获取验证码
                checkIdentifyCodeLoading: false,
                inforValidate: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    cellphone: [
                        {required: true, message: '请输入手机号码'},
                        {validator: validePhone}
                    ]
                },
                editPasswordForm: {
                    oldPass: '',
                    newPass: '',
                    rePass: ''
                },
                passwordValidate: {
                    oldPass: [
                        {required: true, message: '请输入原密码', trigger: 'blur'}
                    ],
                    newPass: [
                        {required: true, message: '请输入新密码', trigger: 'blur'},
                        {min: 6, message: '请至少输入6个字符', trigger: 'blur'},
                        {max: 32, message: '最多输入32个字符', trigger: 'blur'}
                    ],
                    rePass: [
                        {required: true, message: '请再次输入新密码', trigger: 'blur'},
                        {validator: valideRePassword, trigger: 'blur'}
                    ]
                },
                inputCodeVisible: false, // 显示填写验证码box
                initPhone: '',
                gettingIdentifyCodeBtnContent: '获取验证码'  // “获取验证码”按钮的文字
            };
        },
        methods: {
            getIdentifyCode() {
                this.hasGetIdentifyCode = true;
                this.$refs['userForm'].validate((valid) => {
                    if (valid) {
                        this.canGetIdentifyCode = true;
                        let timeLast = 60;
                        let timer = setInterval(() => {
                            if (timeLast >= 0) {
                                this.gettingIdentifyCodeBtnContent = timeLast + '秒后重试';
                                timeLast -= 1;
                            } else {
                                clearInterval(timer);
                                this.gettingIdentifyCodeBtnContent = '获取验证码';
                                this.canGetIdentifyCode = false;
                            }
                        }, 1000);
                        this.inputCodeVisible = true;
                        // you can write ajax request here
                    }
                });
            },
            showEditPassword() {
                this.editPasswordModal = true;
            },
            cancelEditUserInfor() {
                this.$store.commit('removeTag', 'ownspace_index');
                localStorage.pageOpenedList = JSON.stringify(this.$store.state.pageOpenedList);
                let lastPageName = '';
                if (this.$store.state.pageOpenedList.length > 1) {
                    lastPageName = this.$store.state.pageOpenedList[1].name;
                } else {
                    lastPageName = this.$store.state.pageOpenedList[0].name;
                }
                this.$router.push({
                    name: lastPageName
                });
            },
            saveEdit() {
                this.$refs['userForm'].validate((valid) => {
                    if (valid) {
                        if (this.phoneHasChanged && this.userForm.cellphone !== this.initPhone) {  // 手机号码修改过了而且修改之后的手机号和原来的不一样
                            if (this.hasGetIdentifyCode) { // 判断是否点了获取验证码
                                if (this.identifyCodeRight) {  // 判断验证码是否正确
                                    this.saveInfoAjax();
                                } else {
                                    this.$Message.error('验证码错误，请重新输入');
                                }
                            } else {
                                this.$Message.warning('请先点击获取验证码');
                            }
                        } else {
                            this.saveInfoAjax();
                        }
                    }
                });
            },
            cancelEditPass() {
                this.editPasswordModal = false;
                this.resetForm('editPasswordForm');
            },
            saveEditPass() {
                this.$refs['editPasswordForm'].validate((valid) => {
                    if (valid) {
                        modPwd(this.uid, this.editPasswordForm.oldPass, this.editPasswordForm.newPass).then((res) => {
                            if (res.code === 0) {
                                this.$Message.info(res.msg);
                                this.editPasswordModal = false;
                                this.resetForm('editPasswordForm');
                            }
                        });
                    }
                });
            },
            init() {
                const user = JSON.parse(Cookies.get('user'));
                this.uid = user.user_acc;
                this.userForm.name = user.user_name;
                if (user.user_role == Constant.ROLE_HR) {
                    this.userForm.role = '人事';
                } else if (user.user_role == Constant.ROLE_OPERATION) {
                    this.userForm.role = '行政';
                } else if (user.user_role == Constant.ROLE_ADMIN) {
                    this.userForm.role = '管理员';
                }
            },
            cancelInputCodeBox() {
                this.inputCodeVisible = false;
                this.userForm.cellphone = this.initPhone;
            },
            submitCode() {
                let vm = this;
                vm.checkIdentifyCodeLoading = true;
                if (this.securityCode.length === 0) {
                    this.$Message.error('请填写短信验证码');
                } else {
                    setTimeout(() => {
                        this.$Message.success('验证码正确');
                        this.inputCodeVisible = false;
                        this.checkIdentifyCodeLoading = false;
                    }, 1000);
                }
            },
            hasChangePhone() {
                this.phoneHasChanged = true;
                this.hasGetIdentifyCode = false;
                this.identifyCodeRight = false;
            },
            saveInfoAjax() {
                this.save_loading = true;
                setTimeout(() => {
                    this.$Message.success('保存成功');
                    this.save_loading = false;
                }, 1000);
            },
            resetForm(form) {
                this.$refs[form].resetFields();
            },
        },
        mounted() {
            this.init();
        }
    };
</script>
